package com.starxg.m3u8;

import com.starxg.m3u8.gui.DialogUtils;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import com.starxg.m3u8.config.ApplicationConfig;
import com.starxg.m3u8.controller.BaseController;

import java.io.File;
import java.io.IOException;

/**
 * M3U8Application
 *
 * @author huangxingguang@lvmama.com
 * @date 2020-08-12 22:56
 */
@Slf4j
public class M3U8Application extends Application {
    private static ApplicationConfig config;
    private static M3U8Application application;

    public static void main(String[] args) {

        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        application = this;

        log.info("程序启动");

        config = ApplicationConfig.to(new File(ApplicationConfig.DEFAULT_SYNC_FILE));

        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
        Parent root = loader.load();
        ((BaseController) loader.getController()).setStage(stage);

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle(config.getWindow().getTitle());
        stage.setWidth(config.getWindow().getWeight());
        stage.setHeight(config.getWindow().getHeight());
        initEvent(stage);

        stage.show();
    }

    private void initEvent(Stage stage) {
        stage.setOnCloseRequest(e -> {

            if (!DialogUtils.confirm("你确定要退出吗？", stage)) {
                e.consume();
                return;
            }

            log.info("程序关闭中...");

            try {
                config.sync();
            } catch (IOException ex) {
                log.error("持久化配置文件失败，原因：{}", ex.getMessage());
            } finally {
                log.info("程序关闭");
            }

            System.exit(0);

        });

        stage.widthProperty().addListener(
                (observable, oldValue, newValue) -> config.getWindow().setWeight(Math.abs(newValue.intValue() - 20)));
        stage.heightProperty().addListener(
                (observable, oldValue, newValue) -> config.getWindow().setHeight(Math.abs(newValue.intValue() - 20)));

    }

    public static M3U8Application getApplication() {
        return application;
    }
}
